package cn.edu.baiyunu.myapplication.ui.screens.transactions.components

import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.core.tween
import androidx.compose.animation.slideInHorizontally
import androidx.compose.animation.slideOutHorizontally
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.foundation.lazy.grid.items
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Close
import androidx.compose.material3.Icon
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.OutlinedTextFieldDefaults
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import cn.edu.baiyunu.myapplication.data.model.Category
import cn.edu.baiyunu.myapplication.ui.screens.transactions.viewmodel.TransactionFilter

/**
 * 交易筛选菜单
 * 
 * @param isVisible 是否显示
 * @param allCategories 所有分类
 * @param currentFilter 当前筛选条件
 * @param onFilterChanged 筛选条件变更回调
 * @param onCloseClick 关闭按钮点击回调
 * @param onApplyClick 应用筛选按钮点击回调
 * @param onResetClick 重置筛选按钮点击回调
 */
@Composable
fun FilterMenu(
    isVisible: Boolean,
    allCategories: List<Category>,
    currentFilter: TransactionFilter,
    onFilterChanged: (TransactionFilter) -> Unit,
    onCloseClick: () -> Unit,
    onApplyClick: () -> Unit,
    onResetClick: () -> Unit
) {
    var filter by remember { mutableStateOf(currentFilter) }
    val scrollState = rememberScrollState()
    
    // 在初始显示和currentFilter变化时更新内部状态
    androidx.compose.runtime.LaunchedEffect(currentFilter, isVisible) {
        if (isVisible) {
            filter = currentFilter
        }
    }
    
    AnimatedVisibility(
        visible = isVisible,
        enter = slideInHorizontally(
            initialOffsetX = { it },
            animationSpec = tween(durationMillis = 300)
        ),
        exit = slideOutHorizontally(
            targetOffsetX = { it },
            animationSpec = tween(durationMillis = 300)
        )
    ) {
        Box(
            modifier = Modifier
                .fillMaxHeight()
                .width(320.dp)
                .background(Color(0xFF232323).copy(alpha = 0.95f))
                .padding(20.dp)
        ) {
            Column(
                modifier = Modifier
                    .fillMaxWidth()
                    .verticalScroll(scrollState)
            ) {
                // 标题和关闭按钮
                Row(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(bottom = 30.dp),
                    horizontalArrangement = Arrangement.SpaceBetween,
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    Text(
                        text = "筛选交易",
                        color = Color.White,
                        fontSize = 20.sp,
                        fontWeight = FontWeight.Bold
                    )
                    
                    Box(
                        modifier = Modifier
                            .size(30.dp)
                            .clip(CircleShape)
                            .clickable(onClick = onCloseClick),
                        contentAlignment = Alignment.Center
                    ) {
                        Icon(
                            imageVector = Icons.Default.Close,
                            contentDescription = "关闭",
                            tint = Color.White
                        )
                    }
                }
                
                // 交易类型筛选
                Text(
                    text = "交易类型",
                    color = Color.White,
                    fontSize = 16.sp,
                    modifier = Modifier.padding(bottom = 15.dp)
                )
                
                Row(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(bottom = 25.dp)
                ) {
                    FilterOption(
                        text = "全部",
                        isSelected = filter.type == null,
                        modifier = Modifier.weight(1f)
                    ) {
                        filter = filter.copy(type = null)
                    }
                    
                    Spacer(modifier = Modifier.width(10.dp))
                    
                    FilterOption(
                        text = "支出",
                        isSelected = filter.type == "expense",
                        modifier = Modifier.weight(1f)
                    ) {
                        filter = filter.copy(type = "expense")
                    }
                    
                    Spacer(modifier = Modifier.width(10.dp))
                    
                    FilterOption(
                        text = "收入",
                        isSelected = filter.type == "income",
                        modifier = Modifier.weight(1f)
                    ) {
                        filter = filter.copy(type = "income")
                    }
                }
                
                // 分类筛选
                Text(
                    text = "分类",
                    color = Color.White,
                    fontSize = 16.sp,
                    modifier = Modifier.padding(bottom = 15.dp)
                )
                
                LazyVerticalGrid(
                    columns = GridCells.Fixed(3),
                    modifier = Modifier
                        .fillMaxWidth()
                        .height(
                            when {
                                allCategories.size <= 3 -> 50.dp
                                allCategories.size <= 6 -> 110.dp
                                else -> 170.dp
                            }
                        ),
                    horizontalArrangement = Arrangement.spacedBy(10.dp),
                    verticalArrangement = Arrangement.spacedBy(10.dp)
                ) {
                    items(allCategories) { category ->
                        val isSelected = filter.categoryIds.contains(category.id)
                        CategoryFilterItem(
                            name = category.name,
                            isSelected = isSelected
                        ) {
                            val newCategoryIds = if (isSelected) {
                                filter.categoryIds - category.id
                            } else {
                                filter.categoryIds + category.id
                            }
                            filter = filter.copy(categoryIds = newCategoryIds)
                        }
                    }
                }
                
                Spacer(modifier = Modifier.height(25.dp))
                
                // 金额范围筛选
                Text(
                    text = "金额范围",
                    color = Color.White,
                    fontSize = 16.sp,
                    modifier = Modifier.padding(bottom = 15.dp)
                )
                
                Row(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(horizontal = 10.dp),
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    AmountFilterField(
                        value = filter.minAmount?.toString() ?: "",
                        onValueChange = { value ->
                            val amount = value.toDoubleOrNull()
                            filter = filter.copy(minAmount = amount)
                        },
                        placeholder = "最小金额",
                        modifier = Modifier.weight(1f)
                    )
                    
                    Spacer(modifier = Modifier.width(10.dp))
                    
                    Text(
                        text = "-",
                        color = Color.White,
                        fontSize = 16.sp
                    )
                    
                    Spacer(modifier = Modifier.width(10.dp))
                    
                    AmountFilterField(
                        value = filter.maxAmount?.toString() ?: "",
                        onValueChange = { value ->
                            val amount = value.toDoubleOrNull()
                            filter = filter.copy(maxAmount = amount)
                        },
                        placeholder = "最大金额",
                        modifier = Modifier.weight(1f)
                    )
                }
                
                Spacer(modifier = Modifier.height(40.dp))
                
                // 底部操作按钮
                Row(
                    modifier = Modifier.fillMaxWidth(),
                    horizontalArrangement = Arrangement.spacedBy(10.dp)
                ) {
                    FilterActionButton(
                        text = "重置",
                        backgroundColor = Color(0xFFFF5E62).copy(alpha = 0.2f),
                        modifier = Modifier.weight(1f),
                        onClick = onResetClick
                    )
                    
                    FilterActionButton(
                        text = "应用",
                        backgroundColor = Color(0xFF26DE81).copy(alpha = 0.2f),
                        modifier = Modifier.weight(1f),
                        onClick = {
                            onFilterChanged(filter)
                            onApplyClick()
                        }
                    )
                }
            }
        }
    }
}

/**
 * 筛选选项组件
 */
@Composable
private fun FilterOption(
    text: String,
    isSelected: Boolean,
    modifier: Modifier = Modifier,
    onClick: () -> Unit
) {
    Box(
        modifier = modifier
            .clip(RoundedCornerShape(10.dp))
            .background(
                if (isSelected) Color.White.copy(alpha = 0.25f)
                else Color.White.copy(alpha = 0.1f)
            )
            .clickable(onClick = onClick)
            .padding(vertical = 10.dp),
        contentAlignment = Alignment.Center
    ) {
        Text(
            text = text,
            color = Color.White,
            fontSize = 14.sp
        )
    }
}

/**
 * 分类筛选项组件
 */
@Composable
private fun CategoryFilterItem(
    name: String,
    isSelected: Boolean,
    onClick: () -> Unit
) {
    Box(
        modifier = Modifier
            .clip(RoundedCornerShape(10.dp))
            .background(
                if (isSelected) Color.White.copy(alpha = 0.25f)
                else Color.White.copy(alpha = 0.1f)
            )
            .clickable(onClick = onClick)
            .padding(vertical = 10.dp, horizontal = 5.dp),
        contentAlignment = Alignment.Center
    ) {
        Text(
            text = name,
            color = Color.White,
            fontSize = 12.sp
        )
    }
}

/**
 * 金额输入框组件
 */
@Composable
private fun AmountFilterField(
    value: String,
    onValueChange: (String) -> Unit,
    placeholder: String,
    modifier: Modifier = Modifier
) {
    OutlinedTextField(
        value = value,
        onValueChange = onValueChange,
        placeholder = {
            Text(
                text = placeholder,
                color = Color.White.copy(alpha = 0.5f),
                fontSize = 14.sp
            )
        },
        keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number),
        colors = OutlinedTextFieldDefaults.colors(
            focusedBorderColor = Color.White.copy(alpha = 0.3f),
            unfocusedBorderColor = Color.White.copy(alpha = 0.2f),
            focusedTextColor = Color.White,
            unfocusedTextColor = Color.White
        ),
        modifier = modifier,
        singleLine = true,
        textStyle = androidx.compose.ui.text.TextStyle(
            fontSize = 14.sp
        )
    )
}

/**
 * 筛选操作按钮
 */
@Composable
private fun FilterActionButton(
    text: String,
    backgroundColor: Color,
    modifier: Modifier = Modifier,
    onClick: () -> Unit
) {
    Box(
        modifier = modifier
            .clip(RoundedCornerShape(10.dp))
            .background(backgroundColor)
            .clickable(onClick = onClick)
            .padding(vertical = 15.dp),
        contentAlignment = Alignment.Center
    ) {
        Text(
            text = text,
            color = Color.White,
            fontSize = 14.sp
        )
    }
} 